package com.zhenhunfan;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.util.Iterator;
import java.util.concurrent.TimeUnit;

/**
 * <p>Title: 服务端流式RPC，客户端监听异步方式</p>
 * <p>Description:</p>
 *
 * @author zhanghong
 * @date 2023/7/17
 */
public class HelloGrpcClient3 {
    public static void main(String[] args) {
        //1.创建通信的管道
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 9000)
                .usePlaintext().build();
        try {
            //2.获得代理对象 stub

            HelloServiceGrpc.HelloServiceStub helloServiceStub = HelloServiceGrpc.newStub(managedChannel);
            //3.完成rpc调用
            //3.1 准备参数request和response
            HelloProto.HelloRequest.Builder builder = HelloProto.HelloRequest.newBuilder();
            builder.setName("镇魂帆");
            HelloProto.HelloRequest helloRequest = builder.build();

            /*
                  Response 有3个事件  onNext()  onError()   onCompleted()
                  StreamObserver接口就有这三个事件
             */

            //3.2 进行功能rpc调用，获取响应的内容
            helloServiceStub.c2ss(helloRequest, new StreamObserver<HelloProto.HelloResponse>() {
                /**
                 * 服务端响应了一个消息监听事件
                 * @param helloResponse 响应
                 */
                @Override
                public void onNext(HelloProto.HelloResponse helloResponse) {
                    System.out.println(helloResponse.getResult());
                }

                @Override
                public void onError(Throwable throwable) {

                }

                /**
                 * 全部传输完事件
                 */
                @Override
                public void onCompleted() {

                }
            });

            //如果没有下面这样，就看不到响应结果，因为上面代码是异步的，没有阻塞的执行下去，直接进程结束了
            managedChannel.awaitTermination(1, TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            managedChannel.shutdown();
        }
    }
}
